package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.RiverTransition;
import cn.stylefeng.guns.modular.business.enums.RiverTransitionExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.RiverTransitionMapper;
import cn.stylefeng.guns.modular.business.pojo.RiverTransitionRequest;
import cn.stylefeng.guns.modular.business.service.RiverTransitionService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 河道变迁与治理业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/08 16:51
 */
@Service
public class RiverTransitionServiceImpl extends ServiceImpl<RiverTransitionMapper, RiverTransition> implements RiverTransitionService {

    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(RiverTransitionRequest riverTransitionRequest) {
        RiverTransition riverTransition = new RiverTransition();
        BeanUtil.copyProperties(riverTransitionRequest, riverTransition);
        this.save(riverTransition);
    }

    @Override
    public void del(RiverTransitionRequest riverTransitionRequest) {
        RiverTransition riverTransition = this.queryRiverTransition(riverTransitionRequest);
        this.removeById(riverTransition.getId());
    }

    @Override
    public void edit(RiverTransitionRequest riverTransitionRequest) {
        RiverTransition riverTransition = this.queryRiverTransition(riverTransitionRequest);
        BeanUtil.copyProperties(riverTransitionRequest, riverTransition);
        this.updateById(riverTransition);
    }

    @Override
    public RiverTransition detail(RiverTransitionRequest riverTransitionRequest) {
        return this.queryRiverTransition(riverTransitionRequest);
    }

    @Override
    public PageResult<Map<String, Object>> findPage(RiverTransitionRequest riverTransitionRequest) {
        LambdaQueryWrapper<RiverTransition> wrapper = createWrapper(riverTransitionRequest);
        Page<RiverTransition> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        PageResult<RiverTransition> riverTransitionPageResult = PageResultFactory.createPageResult(sysRolePage);
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        List<RiverTransition> riverTransitionList = riverTransitionPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(RiverTransition riverTransition :riverTransitionList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.BQZL+riverTransition.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",riverTransition.getTrTitle());
            map.put("rhdAnnalsfrom",riverTransition.getRhdAnnalsfrom());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(riverTransitionPageResult.getPageSize());
        pageResult.setPageNo(riverTransitionPageResult.getPageNo());
        pageResult.setTotalPage(riverTransitionPageResult.getTotalPage());
        pageResult.setTotalRows(riverTransitionPageResult.getTotalRows());
        return pageResult;
    }

    @Override
    public List<Map<String, Object>> toReview(String jmid) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmid, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.BQZL,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(RiverTransitionExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<RiverTransition> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();

            return mapLists;
        }else {
            queryWrapper.eq(ObjectUtil.isNotEmpty(id), RiverTransition::getId, id);
            List<RiverTransition> riverTransitionList = this.list(queryWrapper);
            if(userid != 0l && userid != -1l) {
                subUseBrowseService.saveBrowse(YunHeKey.HEDAO,riverTransitionList.get(0).getTrTitle(),userid,request);
            }
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (RiverTransition riverTransition : riverTransitionList) {

                Map<String, Object> map = new HashMap<String, Object>();
                map = JSONObject.parseObject(JSONObject.toJSONString(riverTransition), Map.class);

                // 获取类的属性
                Field[] declaredFields = RiverTransition.class.getDeclaredFields();
                List<Map<String, Object>> mplist = new ArrayList<>();
                // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
                if (declaredFields.length != 0) {

                    int i = 1;
                    Map<String, Object> p = new HashMap<String, Object>();

                    for (Field field : declaredFields) {

                        Map<String, Object> mp = new HashMap<String, Object>();
                        if (field.getAnnotation(ApiModelProperty.class) != null) {
                            //获取注解属性
                            ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                            // key和value可根据需求存
                            // 这存的key为注解的值，value为类属性名
                            //把简介提出来
                            if ("trTitle".equals(field.getName()) || "transitionGovern".equals(field.getName())) {
                                if ("trTitle".equals(field.getName())) { //标题
                                    p.put("title", map.get(field.getName()));
                                }else {
                                    p.put(field.getName(), map.get(field.getName()));
                                }
                            }else{
                                mp.put("key", aa.value());
                                mp.put("value", map.get(field.getName()));

                                if (i != 1) {
                                    mplist.add(mp);
                                }
                            }
                        }
                        i++;
                    }

                    p.put("list", mplist);
                    if (i != 1) {
                        mapList.add(p);
                    }
                }
            }
            return mapList;
        }
    }

    @Override
    public List<RiverTransition> findList(RiverTransitionRequest riverTransitionRequest) {
        LambdaQueryWrapper<RiverTransition> wrapper = this.createWrapper(riverTransitionRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private RiverTransition queryRiverTransition(RiverTransitionRequest riverTransitionRequest) {
        RiverTransition riverTransition = this.getById(riverTransitionRequest.getId());
        if (ObjectUtil.isEmpty(riverTransition)) {
            throw new ServiceException(RiverTransitionExceptionEnum.RIVERTRANSITION_NOT_EXISTED);
        }
        return riverTransition;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/08 16:51
     */
    private LambdaQueryWrapper<RiverTransition> createWrapper(RiverTransitionRequest riverTransitionRequest) {
        LambdaQueryWrapper<RiverTransition> queryWrapper = new LambdaQueryWrapper<>();

        Long id = riverTransitionRequest.getId();
        String riverName = riverTransitionRequest.getRiverName();
        String rtFirst = riverTransitionRequest.getRtFirst();
        String rtSecond = riverTransitionRequest.getRtSecond();
        String rtThrid = riverTransitionRequest.getRtThrid();
        String historyDating = riverTransitionRequest.getHistoryDating();
        String theCommon = riverTransitionRequest.getTheCommon();
        String transitionGovern = riverTransitionRequest.getTransitionGovern();
        String quoteAnnotation = riverTransitionRequest.getQuoteAnnotation();
        String rhdAnnalsfrom = riverTransitionRequest.getRhdAnnalsfrom();
        String rhdAnnalspage = riverTransitionRequest.getRhdAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), RiverTransition::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(riverName), RiverTransition::getRiverName, riverName);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtFirst), RiverTransition::getRtFirst, rtFirst);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtSecond), RiverTransition::getRtSecond, rtSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(rtThrid), RiverTransition::getRtThrid, rtThrid);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), RiverTransition::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), RiverTransition::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(transitionGovern), RiverTransition::getTransitionGovern, transitionGovern);
        queryWrapper.like(ObjectUtil.isNotEmpty(quoteAnnotation), RiverTransition::getQuoteAnnotation, quoteAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalsfrom), RiverTransition::getRhdAnnalsfrom, rhdAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(rhdAnnalspage), RiverTransition::getRhdAnnalspage, rhdAnnalspage);

        return queryWrapper;
    }

}